// ignore: file_names
// 数据库管理：books

// ignore_for_file: unused_local_variable
import 'package:sqflite/sqflite.dart';

// ignore: camel_case_types
class booksManager {
  final sqlFileName = "books.sql"; //sql文件
  final table = "books"; //表名
  // var id = 0;
  // var bookName = ""; //书名
  // var content = []; //内容
  // var catalogue = []; //目录
  // var bookmark = ""; //书签
  // var path = ""; //路径
  late Database database;
  // 数据库初始化
  Future<void> initializeDatabase() async {
    database = await openDatabase(
      'iBook.db',
      version: 1,
      onCreate: _createDatabase,
    );
    try {
      await database.rawQuery('SELECT 1 FROM books LIMIT 1');
    } catch (e) {
      // 如果捕获到异常，表不存在，可以手动调用创建数据库表格
      _createDatabase(database, 1);
    }
    // _createDatabase(database, 1); // 手动调用创建数据库表格
  }

  void _createDatabase(Database db, int version) async {
    // 创建小说表
    await db.execute('''
    CREATE TABLE books (
      id integer,
      bookName TEXT,
      name TEXT,
      content TEXT,
      catalogue TEXT,
      bookmark TEXT,
      path TEXT
    )
  ''');
  }

  // 验证小说内容表是否存在，不存在就创建
  Future<void> initializeContentDatabase(bookName) async {
    try {
      await database.rawQuery('SELECT 1 FROM $bookName LIMIT 1');
    } catch (e) {
      _createContentDatabase(database, 1, bookName);
    }
  }

  // 如果捕获到异常，表不存在，可以手动调用创建数据库表格
  void _createContentDatabase(Database db, int version, bookName) async {
    // 创建小说内容表
    await db.execute('''
    CREATE TABLE $bookName (
      id integer,
      title TEXT,
      chapter TEXT
    )
  ''');
  }

  // 插入books表
  Future<int> insertBook(Map<String, dynamic> book) async {
    final db = await database;
    final books = await getAllBooks();
    book['id'] = books.length;
    String contentTableName = "table_${books.length}";
    book['content'] = contentTableName;
    var flag = 0;
    books.forEach((item) => {
          if (book['bookName'] == item["bookName"]) {flag = 1}
        });
    if (flag == 0) {
      print("插入表中数据成功");
      await db.insert('books', book);
      // 创建文本内容表 以id_table命名
      initializeContentDatabase(contentTableName);
      return 1;
    } else
      return 0;
  }

  // 查询books表中所有数据
  Future<List<Map<String, dynamic>>> getAllBooks() async {
    final db = await database;
    print("查询所有书籍成功");
    return await db.query('books');
  }

  // 查询books表中指定数据
  Future<List<Map<String, Object?>>> getBookInfo(bookname) async {
    final db = await database;
    print("查询指定书籍成功");
    return await db.query('books', where: "bookName=?", whereArgs: [bookname]);
  }

  // 更新books表中的指定字段
  Future<void> updateBookInfo(id, key, value) async {
    final db = await database;
    print("bookname: $id, key: $key, value: $value");
    await db.update('books', {key: value}, where: "id=?", whereArgs: [id]);
    print("更新表中数据成功");
  }

  // 插入bookContent表
  Future<void> insertContentTable(String bookname, int id, String title, String chapter) async {
    final db = await database;
    try {
      await db.insert(bookname, {'id': id, 'title': title, 'chapter': chapter});
      print("插入成功");
    } catch (e) {
      print("插入失败");
    }
    // print("更新表中数据成功");
  }

  // 查询bookContent表中所有数据
  Future<List<Map<String, dynamic>>> getBookContent(String bookname) async {
    final db = await database;
    print("查询总内容成功");
    return await db.query('$bookname');
  }

// 添加分页查询方法
  Future<List<Map<String, Object?>>> getBookContentByPage(String tableName, {int limit = 1, int offset = 0}) async {
    return await database.rawQuery('SELECT id, title FROM $tableName LIMIT ? OFFSET ?', [limit, offset]);
  }

  // 查询bookContent表中指定数据
  Future<List<Map<String, dynamic>>> getBookContentInfo(String bookname, int start, int end) async {
    final db = await database;
    print("查询数据内容成功");
    return await db.query('$bookname', where: "id>=? and id<?", whereArgs: [start, end]);
  }

  // 删除表中指定的数据
  Future<void> deleteRowDataFromBooks(value) async {
    final db = await database;
    var res = await getBookInfo(value);
    String contentTableName = res[0]['content'].toString();
    await db.delete("books", where: 'bookName = ?', whereArgs: [value + '']);
    await db.execute("drop table if exists $contentTableName");
    print("删除成功！" + value);
  }

  // 删除表
  Future<void> deleteTableBooks() async {
    final db = await database;
    await db.execute("drop table if exists books");
    print("删除表成功");
  }

  // 删除表中所有数据
  Future<void> deleteDataFromBooks() async {
    final db = await database;
    await db.delete("books");
    print("删除表中数据成功");
  }

  // 删除表中所有数据
  Future<void> deleteDataFromBookContent(bookName) async {
    final db = await database;
    await db.delete("$bookName");
    print("删除表中数据成功");
  }

  // 关闭数据库
  closeDataBase() {
    database.close();
  }
}
